package cn.com.bob.messageboard.controller;

import cn.com.bob.messageboard.domain.JsonResult;
import cn.com.bob.messageboard.domain.Message;
import cn.com.bob.messageboard.service.MessageService;
import cn.com.bob.messageboard.utils.ExcelExportUtil;
import cn.com.bob.messageboard.utils.JwtTokenUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static cn.com.bob.messageboard.controller.BaseController.OK;

/**
 * @Author Bob
 * @Version：1.0
 */

@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/getListByPage")
    public List<Message> getListByPage(int pageNo, int pageSize){
        Page<Message> page = messageService.getMsgByPage(pageNo, pageSize);
        List<Message> list = page.getRecords();
        return list;
    }

    @GetMapping("/getAll")
    public List<Message> getAll(){
        return messageService.getAllMsg();
    }

    @PostMapping("/add")
    public JsonResult<Message> add(@RequestBody Message msg,HttpServletRequest request){
        String jwt = request.getHeader("Authorization");
        String username = JwtTokenUtil.getUserName(jwt);
        messageService.addMsg(username, msg.getContent());
        Message message = new Message();
        message.setUsername(username);
        message.setContent(msg.getContent());
        return new JsonResult<>(OK,message);
    }

    @GetMapping("/search")
    public JsonResult<List<Message>> search(@RequestParam("keyword") String keyword){
        List<Message> data = messageService.getMsgByName(keyword);
        return new JsonResult<>(OK,data);
    }

    @GetMapping("/exportExcel")
    public JsonResult<Void> export(@PathParam("fileName") String fileName, HttpServletRequest request){
        List<Message> list = messageService.getAllMsg();
        System.out.println(fileName);
        String jwt = request.getHeader("Authorization");
        String username = JwtTokenUtil.getUserName(jwt);
        try {
            ExcelExportUtil.exportExcelByWater(list,fileName,username);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return new JsonResult<>(OK);
    }
}
